from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from article.models import Article
from question.serializers.label_serializers import *
from recruit.models import Enterprise, Recruit
from .models import User
import re


# 标签
class LabelDSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','labels']

#　职位
class RecruitSerializer(serializers.ModelSerializer):
    class Meta:
        model = Recruit
        fields = '__all__'

# 企业
class EnterpriseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Enterprise
        fields = ['id','name','labels','logo','recruits','summary']

# 文章嵌套user的articles
class UserArticlesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = [
            'id',
            'title'
        ]

# fans
class FansSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id','username']

# 个人详情user
class UserSerializer(serializers.ModelSerializer):
    articles = UserArticlesSerializer(many=True,read_only=True)
    fans = FansSerializer(many=True,source='idols')
    class Meta:
        model = User
        fields = '__all__'

# 文章
class ArticleSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = Article
        fields = '__all__'

# 回复的自关联
class SubsSerializer(serializers.ModelSerializer):
    user = UserSerializer(write_only=True)
    class Meta:
        model = Reply
        exclude = ['problem']

# 回复
class ReplySerializer(serializers.ModelSerializer):
    subs = SubsSerializer()
    user = UserSerializer()
    class Meta:
        model = Reply

        fields = '__all__'

# 个人详情页
class UserDetailSerializer(serializers.ModelSerializer):
    labels = LabelSerializer(many=True,required=False)
    questions = QuestionsSerializer(many=True,required=False)
    answer_question = ReplySerializer(many=True,required=False,source='replies')
    collected_articles = ArticleSerializer(many=True,required=False)
    enterpises = EnterpriseSerializer(many=True,required = False)
    class Meta:
        model = User

        fields = '__all__'

        extra_kwargs = {
            'username': {'required': False},
            'password': {'required': False,'write_only':True},
            'fans': {'required': False},
        }

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        realname = attrs.get('realname')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            raise serializers.ValidationError("mobile格式不对")

        if not re.match(r'^([\u4e00-\u9fa5\·]{1,20}|[a-zA-Z\.\s]{1,20})$',realname):
            raise serializers.ValidationError('名字的格式有误')
        return attrs

# 注册
class UserRegisterSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','password','mobile','avatar']
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def validate(self, attrs):
        password = attrs.get('password')
        mobile = attrs.get('mobile')
        sms_code = self.initial_data['sms_code']

        # 必要性校验
        if not re.match(r'^[A-Za-z\d]{6,16}$',password):
            raise serializers.ValidationError('password格式不对')

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            raise serializers.ValidationError('mobile格式不对')

        # 短信验证
        redis_conn = get_redis_connection('verify_code')

        #取出短信
        sms_code_server = redis_conn.get('sms_code_%s'%mobile)

        if sms_code_server is None:
            raise serializers.ValidationError('短信验证码过期')

        if sms_code_server.decode() != sms_code:
            raise serializers.ValidationError('输入的验证码有误')

        # 短信加密
        new_password = make_password(password)

        # 替换原来的密码
        attrs['password'] = new_password

        return attrs


    def create(self, validated_data):

        try:
            user = User.objects.create(**validated_data)
        except Exception as e:
            raise serializers.ValidationError('訪問數據庫失敗')

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return {
            'username':user,
            'user': user,
            'token': token
        }


# # 登录
# class UserLoginSerializer(serializers.Serializer):
#
#     username =serializers.CharField(max_length=20,required=True)
#     password = serializers.CharField(min_length=6,max_length=19,required=True)
#
#     def validate(self, attrs):
#         password = attrs.get('password')
#         mobile = attrs.get('username')
#
#         username = User.objects.get(mobile=mobile)
#         if not username:
#             raise serializers.ValidationError('賬號或者密碼錯誤')
#         user = authenticate(username=username,
#                             password=password)
#
#         if not user:
#             raise serializers.ValidationError("賬號或者密碼錯誤")
#
#         payload = jwt_payload_handler(user)
#         token = jwt_encode_handler(payload)
#         return {
#             'user':user,
#             'token':token
#         }
